<!doctype html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Document</title>
	</head>
	<!-- 瀑布流 + 预加载-->
	<style>
		* {
			padding: 0;
			margin: 0;
		}

		.box {
			display: flex;
			align-items: flex-start;
		}

		ul {
			flex: 1;
			margin: 0 5px;
		}

		ul li {
			list-style: none;
			margin-top: 5px;
		}

		ul li img {
			width: 100%;
		}
	</style>

	<body>
		<div class="box">
			<ul></ul>
			<ul></ul>
			<ul></ul>
			<ul></ul>
			<ul></ul>
		</div>

		<script>
			window.onload = function () {
				createImg(20);
			};

			window.onscroll = function () {
				var minHeightUl = getMinHeightUl();
				var h = document.querySelector('.box').offsetHeight;
				const scrollY = window.scrollY;
				const screenY = window.innerHeight;
				if (minHeightUl.offsetHeight < scrollY + screenY) {
					createImg(20);
				}
			};

			function createImg(num) {
				for (let i = 0; i < num; i++) {
					const h = random(400, 600);
					const minHeightUl = getMinHeightUl();
					const li = document.createElement('li');
					const img = document.createElement('img');
					img.style.height = h + 'px';
					img.src = `../assets/img/天空.jpg`;
					// img.src = `https://unsplash.it/250/${h}/?random'`
					li.appendChild(img);
					minHeightUl.appendChild(li);
					let img2 = new Image();
					img2.src = `https://unsplash.it/250/${h}/?random'`;
					img2.onload = function () {
						img.src = `https://unsplash.it/250/${h}/?random'`;
					};
				}
			}

			function getMinHeightUl() {
				const ul = document.querySelectorAll('ul');
				let minHeightIndex = 0;
				for (let i = 0; i < ul.length; i++) {
					const el = ul[i];
					if (el.offsetHeight < ul[minHeightIndex].offsetHeight) {
						minHeightIndex = i;
						break;
					}
				}
				return ul[minHeightIndex];
			}

			function random(min, max) {
				return parseInt(Math.random() * min + (max - min));
			}
		</script>
	</body>
</html>
